#include "SettingLayer.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "SimpleAudioEngine.h"
#include "AudioEngine.h"
#include "GlobalSetting.h"

using namespace experimental;
using namespace CocosDenshion;
using namespace cocos2d::ui;

bool SettingLayer::init() {
	if (!Layer::init()) {
		return false;
	}
	auto node = CSLoader::createNode("SettingLayer.csb");
	this->addChild(node);

	auto music_slider = dynamic_cast<Slider*>(node->getChildByName("music_slider"));
	auto sound_slider = dynamic_cast<Slider*>(node->getChildByName("sound_slider"));
	auto close_btn = dynamic_cast<Button*>(node->getChildByName("close_btn"));
	if (close_btn == nullptr) {
		log("close button is null!");
	}
	else {
		close_btn->addClickEventListener([this](Ref* ref) {
			parent->SetBtnEnable(true);
			this->removeFromParentAndCleanup(true);
		});
	}
	if (music_slider == nullptr) {
		log("music slider is null!");
	}
	else {
		music_slider->setPercent(GlobalSetting::music_volume * 100);
		music_slider->addEventListener([music_slider](Ref* psender, Slider::EventType type) {
			if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) {
				//SimpleAudioEngine::getInstance()->setBackgroundMusicVolume(music_slider->getPercent() / 100.0f);
				AudioEngine::setVolume(GlobalSetting::audio_bg_id, music_slider->getPercent() / 100.0f);
				GlobalSetting::music_volume = music_slider->getPercent() / 100.0f;
			}
		});
	}
	if (sound_slider == nullptr) {
		log("sound slider is null!");
	}
	else {
		sound_slider->setPercent(GlobalSetting::effect_volume * 100);
		sound_slider->addEventListener([sound_slider](Ref* psender, Slider::EventType type) {
			if (type == Slider::EventType::ON_PERCENTAGE_CHANGED) {
				//SimpleAudioEngine::getInstance()->setEffectsVolume(ins->getPercent() / 100.0f);
				GlobalSetting::effect_volume = sound_slider->getPercent() / 100.0f;
			}
		});
	}

	return true;
}

SettingLayer* SettingLayer::create(WelcomeScene* parent) {
	auto _ins = new SettingLayer();
	if (_ins->init()) {
		_ins->autorelease();
		_ins->parent = parent;
		return _ins;
	}
	else {
		delete _ins;
		_ins = nullptr;
		return nullptr;
	}
}